# coding=utf-8
import requests
import base64
from PIL import Image
import cv2
import numpy as np

def gettoken():
    url = 'https://aip.baidubce.com/oauth/2.0/token'
    data = {'grant_type': 'client_credentials',
            'client_id': 'wHC5Hyj9M3jOu1sin5rs8EjD',
            'client_secret': 'SG9G3PFj7HZpoIrCAW1OZ6SauPAm0L3K'}
    headers = {'Content-Type': 'application/json; charset=UTF-8'}
    response = requests.post(url, data=data, headers=headers)
    return response.json()["access_token"]

def division(im_path):
    url = "https://aip.baidubce.com/rest/2.0/image-classify/v1/body_seg"
    #im_path = 'static/images/1535426712.jpg'
    im = Image.open(im_path)
    width, height = im.size
    token = gettoken()
    with open(im_path, 'r') as f:
        image = base64.b64encode(f.read())
    data = {'access_token': token,
            'image': image}
    headers = {"Content-Type": "application/x-www-form-urlencoded"}
    response = requests.post(url, headers=headers, data=data)
    image = base64.b64decode(response.json()['labelmap'])
    nparr = np.fromstring(image, np.uint8)
    labelimg = cv2.imdecode(nparr, 1)
    # width, height为图片原始宽、高
    labelimg = cv2.resize(labelimg, (width, height), interpolation=cv2.INTER_NEAREST)
    #im_new = np.where(labelimg==1, 60, labelimg)
    #cv2.imwrite('static/test2.jpg', im_new)
    return labelimg

#division()
